package utils

import (
	"encoding/json"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"runtime/debug"
	"strings"
)

type ResponseCode int

//1000以下为通用码，1000以上为用户自定义码
const (
	SuccessCode ResponseCode = iota		// 正常请求
	UndefErrorCode						// 不确定的请求
	ValidErrorCode						// 校验失败
	InternalErrorCode					// 内部错误

	MysqlConnectErrorCode ResponseCode = 2000 	//数据库连接错误
	ValidRequestErrorCode ResponseCode = 100	// 参数校验错误
	RequestErrorCode ResponseCode = 400	// 业务请求错误
	InvalidRequestErrorCode ResponseCode = 401	// 无效请求
	NotLoginCode           ResponseCode = 402  // 请先登陆
)

//返回的数据格式
type Response struct {
	ErrorCode ResponseCode `json:"errno"`//错误码  默认0
	Message  string       `json:"message"`//返回的信息
	Data      interface{}  `json:"data"`//返回的数据
	TraceId   interface{}  `json:"trace_id"`//日志跟踪id
	Stack     interface{}  `json:"stack"`//堆栈
}
//错误的返回
// code 错误码  err 错误信息
func Error(c *gin.Context, code ResponseCode, err error) {
	trace, _ := c.Get("trace")
	traceContext, _ := trace.(*lib.TraceContext)
	traceId := ""
	if traceContext != nil {
		traceId = traceContext.TraceId
	}

	// 如果是dev环境 或者 开启debug模式 显示堆栈信息
	var stack = []string{}
	if c.Query("is_debug") == "1" || lib.GetConfEnv() == "dev" {
		stackStr:=strings.Replace(string(debug.Stack()),"\n\t","\n",-1)
		stack = strings.Split(stackStr,"\n")
	}

	resp := &Response{
		ErrorCode: code,
		Message: err.Error(),
		Data: "",
		TraceId: traceId,
		Stack:stack,
	}

	c.JSON(200, resp)
	response, _ := json.Marshal(resp)
	c.Set("response", string(response))
	c.AbortWithError(200, err)
}

//统一封装数据的输出
func Success(c *gin.Context,Message string, data interface{}) {
	trace, _ := c.Get("trace")
	traceContext, _ := trace.(*lib.TraceContext)
	traceId := ""
	if traceContext != nil {
		traceId = traceContext.TraceId
	}
	resp := &Response{
		ErrorCode: SuccessCode,
		Message: Message,
		Data: data,
		TraceId: traceId,
	}
	c.JSON(200, resp)
	response, _ := json.Marshal(resp)
	c.Set("response", string(response))
}
